from flask import Blueprint, jsonify, request, current_app
import uuid
import datetime
import jwt

from src.models.character_models import db, CharacterAnalysis, FortuneForcast
from src.models.bazi_models import BaziRecord
from src.routes.auth import token_required

character_bp = Blueprint('character', __name__)

# 性格分析
@character_bp.route('/analysis', methods=['POST'])
def character_analysis():
    data = request.json
    
    # 验证必要字段
    if not data or not data.get('baziId'):
        return jsonify({
            'code': 400,
            'message': '请提供八字ID',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 400
    
    # 查询八字记录
    bazi_record = BaziRecord.query.filter_by(bazi_id=data.get('baziId')).first()
    if not bazi_record:
        return jsonify({
            'code': 404,
            'message': '未找到相关八字记录',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    # 获取用户ID（如果已登录）
    user_id = None
    token = None
    if 'Authorization' in request.headers:
        auth_header = request.headers['Authorization']
        try:
            token = auth_header.split(" ")[1]
            payload = jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=['HS256'])
            user_id = payload['sub']
        except:
            # 忽略token错误，视为游客访问
            pass
    
    # 生成性格ID
    character_id = f"ch{uuid.uuid4().hex[:10]}"
    
    # 基础性格分析（简化处理）
    basic_summary = f"基于八字{bazi_record.tian_gan}{bazi_record.di_zhi}的性格分析，您的性格特点主要表现为..."
    
    # 付费内容（简化处理）
    strengths = "性格优点详细内容，需要付费查看。"
    weaknesses = "性格缺点详细内容，需要付费查看。"
    relationship_style = "人际关系风格详细内容，需要付费查看。"
    work_style = "工作学习风格详细内容，需要付费查看。"
    improvement_suggestion = "性格优化建议详细内容，需要付费查看。"
    
    # 创建性格分析记录
    character_analysis = CharacterAnalysis(
        character_id=character_id,
        bazi_id=bazi_record.bazi_id,
        user_id=user_id,
        basic_summary=basic_summary,
        strengths=strengths,
        weaknesses=weaknesses,
        relationship_style=relationship_style,
        work_style=work_style,
        improvement_suggestion=improvement_suggestion,
        is_paid=0,
        create_time=datetime.datetime.now(),
        update_time=datetime.datetime.now()
    )
    
    try:
        db.session.add(character_analysis)
        db.session.commit()
        
        # 构建响应数据
        response_data = {
            'characterId': character_id,
            'basicTraits': {
                'summary': basic_summary,
                'strengths': ["善于思考", "责任心强"],
                'weaknesses': ["有时优柔寡断", "过于追求完美"]
            },
            'needPayment': True,
            'paymentInfo': {
                'price': 1.1,
                'memberPrice': 0.1
            }
        }
        
        return jsonify({
            'code': 200,
            'message': '分析成功',
            'data': response_data,
            'timestamp': datetime.datetime.now().timestamp()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'分析失败: {str(e)}',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 500

# 获取性格详细分析（付费内容）
@character_bp.route('/analysis/<character_id>/detail', methods=['GET'])
def get_character_detail(character_id):
    # 查询性格分析
    character_analysis = CharacterAnalysis.query.filter_by(character_id=character_id).first()
    if not character_analysis:
        return jsonify({
            'code': 404,
            'message': '未找到相关性格分析',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    # 检查是否已付费
    if character_analysis.is_paid == 0:
        # 获取用户ID（如果已登录）
        user_id = None
        is_vip = False
        token = None
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            try:
                token = auth_header.split(" ")[1]
                payload = jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=['HS256'])
                user_id = payload['sub']
                
                # 检查是否是VIP会员
                from src.models.user_models import UserVip
                vip_info = UserVip.query.filter_by(user_id=user_id, status=1).first()
                if vip_info and vip_info.expire_time > datetime.datetime.now():
                    is_vip = True
            except:
                # 忽略token错误，视为游客访问
                pass
        
        # 如果不是VIP会员，需要付费
        if not is_vip:
            return jsonify({
                'code': 403,
                'message': '需要付费查看详细分析',
                'data': {
                    'needPayment': True,
                    'paymentInfo': {
                        'price': 1.1,
                        'memberPrice': 0.1
                    }
                },
                'timestamp': datetime.datetime.now().timestamp()
            }), 403
    
    # 构建响应数据
    response_data = {
        'characterId': character_id,
        'basicSummary': character_analysis.basic_summary,
        'detailAnalysis': {
            'strengths': character_analysis.strengths,
            'weaknesses': character_analysis.weaknesses,
            'relationshipStyle': character_analysis.relationship_style,
            'workStyle': character_analysis.work_style,
            'improvementSuggestion': character_analysis.improvement_suggestion
        }
    }
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': response_data,
        'timestamp': datetime.datetime.now().timestamp()
    }), 200

# 今日运势
@character_bp.route('/fortune/daily/<bazi_id>', methods=['GET'])
def get_daily_fortune(bazi_id):
    # 查询八字记录
    bazi_record = BaziRecord.query.filter_by(bazi_id=bazi_id).first()
    if not bazi_record:
        return jsonify({
            'code': 404,
            'message': '未找到相关八字记录',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    # 获取用户ID（如果已登录）
    user_id = None
    token = None
    if 'Authorization' in request.headers:
        auth_header = request.headers['Authorization']
        try:
            token = auth_header.split(" ")[1]
            payload = jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=['HS256'])
            user_id = payload['sub']
        except:
            # 忽略token错误，视为游客访问
            pass
    
    # 检查今日是否已有运势记录
    today = datetime.date.today()
    fortune = FortuneForcast.query.filter_by(
        bazi_id=bazi_id,
        forecast_date=today,
        forecast_type=1
    ).first()
    
    # 如果没有今日运势记录，创建一个
    if not fortune:
        # 生成预测ID
        forecast_id = f"fc{uuid.uuid4().hex[:10]}"
        
        # 生成运势评分（简化处理）
        import random
        overall_score = random.randint(60, 95)
        career_score = random.randint(60, 95)
        wealth_score = random.randint(60, 95)
        love_score = random.randint(60, 95)
        health_score = random.randint(60, 95)
        
        # 运势描述（简化处理）
        overall_desc = f"今日整体运势为{overall_score}分，属于{'较好' if overall_score >= 80 else '一般'}水平。"
        career_desc = "今日事业运势详细内容，需要付费查看。"
        wealth_desc = "今日财运详细内容，需要付费查看。"
        love_desc = "今日感情运势详细内容，需要付费查看。"
        health_desc = "今日健康运势详细内容，需要付费查看。"
        suggestion = "今日行动建议详细内容，需要付费查看。"
        
        # 创建运势预测记录
        fortune = FortuneForcast(
            forecast_id=forecast_id,
            bazi_id=bazi_id,
            user_id=user_id,
            forecast_date=today,
            forecast_type=1,
            overall_score=overall_score,
            career_score=career_score,
            wealth_score=wealth_score,
            love_score=love_score,
            health_score=health_score,
            overall_desc=overall_desc,
            career_desc=career_desc,
            wealth_desc=wealth_desc,
            love_desc=love_desc,
            health_desc=health_desc,
            suggestion=suggestion,
            is_paid=0,
            create_time=datetime.datetime.now(),
            update_time=datetime.datetime.now()
        )
        
        try:
            db.session.add(fortune)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            return jsonify({
                'code': 500,
                'message': f'生成运势失败: {str(e)}',
                'data': None,
                'timestamp': datetime.datetime.now().timestamp()
            }), 500
    
    # 构建响应数据
    response_data = {
        'date': fortune.forecast_date.strftime('%Y-%m-%d'),
        'overall': fortune.overall_score,
        'fortune': {
            'career': fortune.career_score,
            'wealth': fortune.wealth_score,
            'love': fortune.love_score,
            'health': fortune.health_score
        },
        'suggestion': "今日宜：专注工作，谨慎投资。忌：冲动消费，情绪外露。",
        'needPayment': True,
        'paymentInfo': {
            'price': 1.1,
            'memberPrice': 0.1
        }
    }
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': response_data,
        'timestamp': datetime.datetime.now().timestamp()
    }), 200

# 获取运势详细内容（付费）
@character_bp.route('/fortune/<forecast_id>/detail', methods=['GET'])
def get_fortune_detail(forecast_id):
    # 查询运势预测
    fortune = FortuneForcast.query.filter_by(forecast_id=forecast_id).first()
    if not fortune:
        return jsonify({
            'code': 404,
            'message': '未找到相关运势预测',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    # 检查是否已付费
    if fortune.is_paid == 0:
        # 获取用户ID（如果已登录）
        user_id = None
        is_vip = False
        token = None
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            try:
                token = auth_header.split(" ")[1]
                payload = jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=['HS256'])
                user_id = payload['sub']
                
                # 检查是否是VIP会员
                from src.models.user_models import UserVip
                vip_info = UserVip.query.filter_by(user_id=user_id, status=1).first()
                if vip_info and vip_info.expire_time > datetime.datetime.now():
                    is_vip = True
            except:
                # 忽略token错误，视为游客访问
                pass
        
        # 如果不是VIP会员，需要付费
        if not is_vip:
            return jsonify({
                'code': 403,
                'message': '需要付费查看详细运势',
                'data': {
                    'needPayment': True,
                    'paymentInfo': {
                        'price': 1.1,
                        'memberPrice': 0.1
                    }
                },
                'timestamp': datetime.datetime.now().timestamp()
            }), 403
    
    # 构建响应数据
    response_data = {
        'forecastId': fortune.forecast_id,
        'date': fortune.forecast_date.strftime('%Y-%m-%d'),
        'type': fortune.forecast_type,
        'scores': {
            'overall': fortune.overall_score,
            'career': fortune.career_score,
            'wealth': fortune.wealth_score,
            'love': fortune.love_score,
            'health': fortune.health_score
        },
        'descriptions': {
            'overall': fortune.overall_desc,
            'career': fortune.career_desc,
            'wealth': fortune.wealth_desc,
            'love': fortune.love_desc,
            'health': fortune.health_desc
        },
        'suggestion': fortune.suggestion
    }
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': response_data,
        'timestamp': datetime.datetime.now().timestamp()
    }), 200
